var express=require('express')
var bodyParser = require('body-parser')
//  var bodyParser = require('body-parser')
 var fs=require('fs')
var router=express.Router()
router.post('/answer',function(req,res){
    
     function send(code, message){
        res.status(200).json({ code, message})
    }

    
    var aname = req.cookies.petname
    var fileName = 'questions/' + req.cookies.question + '.txt'
    //  console.log(fileName)
    req.body.ip = req.ip
    req.body.time = new Date()
    req.body.petname = aname
    
    fs.readFile(fileName,function(err,data){
        if( err ){
            res.send('保存失败')
        }else{
            var datas = JSON.parse(data)
            // console.log(datas)
            if( !datas.answers ){
                datas.answers = []
            }
            datas.answers.push(req.body)
            fs.writeFile(fileName,JSON.stringify(datas),function(err){
                if(err){
                    send('error', '保存数据失败')
                }else{
                    send('success', '保存数据成功')
                }
            })
        }
    })
})
module.exports=router